package com.zgl.gemduel.controller;

import com.zgl.gemduel.model.RoomResource;
import com.zgl.gemduel.service.RoomResourceService;
import com.zgl.gemduel.utils.RedisService;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/room")
public class RoomController {

    @Autowired
    private RedisService redisService;

    @Autowired
    private RoomResourceService roomResourceService;

    /**
     * 创建房间接口
     * 用户请求后会获得一个房间ID，并且把房间ID和用户IP进行绑定存储到Redis
     *
     * @param request HTTP请求对象，用于获取用户IP
     * @return 包含房间ID的响应
     */
    @PostMapping("/create")
    public Map<String, Object> createRoom(HttpServletRequest request) {
        // 生成唯一的房间ID
        String roomId = UUID.randomUUID().toString().substring(0, 8);
        
        // 获取用户IP地址
        String userIp = getClientIpAddress(request);
        
        // 将房间ID与用户IP绑定存储到Redis
        // 使用房间ID作为key，用户IP作为value
        redisService.setWithExpire("room:" + roomId, userIp, 24, TimeUnit.HOURS);
        
        // 同时存储反向映射，方便通过IP查找房间
        redisService.setWithExpire("ip:" + userIp + ":room", roomId, 24, TimeUnit.HOURS);
        
        // 初始化房间资源
        roomResourceService.initializeRoomResource(roomId);
        
        // 构造返回结果
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("roomId", roomId);
        response.put("message", "房间创建成功");
        
        return response;
    }

    /**
     * 通过IP查询房间号接口
     * 
     * @param request HTTP请求对象，用于获取用户IP
     * @return 包含房间ID的响应
     */
    @GetMapping("/query")
    public Map<String, Object> queryRoomByIp(HttpServletRequest request) {
        // 获取用户IP地址
        String userIp = getClientIpAddress(request);
        
        // 从Redis中查询该IP对应的房间ID
        Object roomIdObj = redisService.get("ip:" + userIp + ":room");
        
        // 构造返回结果
        Map<String, Object> response = new HashMap<>();
        
        if (roomIdObj != null) {
            String roomId = roomIdObj.toString();
            response.put("success", true);
            response.put("roomId", roomId);
            response.put("message", "查询成功");
        } else {
            response.put("success", false);
            response.put("roomId", null);
            response.put("message", "未找到该IP对应的房间");
        }
        
        return response;
    }

    /**
     * 获取房间资源信息
     * 
     * @param roomId 房间ID
     * @return 房间资源信息
     */
    @GetMapping("/resource/{roomId}")
    public Map<String, Object> getRoomResource(@PathVariable String roomId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            RoomResource roomResource = roomResourceService.getRoomResource(roomId);
            
            if (roomResource != null) {
                response.put("success", true);
                response.put("data", roomResource);
                response.put("message", "获取房间资源成功");
            } else {
                response.put("success", false);
                response.put("data", null);
                response.put("message", "未找到该房间资源");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("data", null);
            response.put("message", "获取房间资源失败: " + e.getMessage());
        }
        
        return response;
    }

   /**
    * 添加玩家到房间
    * @param roomId 房间id
    * @param request
    * @return
    */
   @PostMapping("/addPlayer/{roomId}")
   public Map<String, Object> addPlayerToRoom(@PathVariable String roomId, HttpServletRequest request) {
       Map<String, Object> response = new HashMap<>();
       // 获取用户IP地址
       String userIp = getClientIpAddress(request);
       try {
           roomResourceService.addPlayerToRoom(roomId, userIp);
           response.put("success", true);
           response.put("message", "玩家添加成功");
           response.put("userIp", userIp);
       } catch (Exception e) {
           response.put("success", false);
           response.put("message", "添加玩家失败: " + e.getMessage());
       }

       return response;
   }

    // @PostMapping("/addPlayer/{roomId}")
    // public Map<String, Object> addPlayerToRoom(@PathVariable String roomId, @RequestParam String userIp) {
    //     Map<String, Object> response = new HashMap<>();

    //     try {
    //         roomResourceService.addPlayerToRoom(roomId, userIp);
    //         response.put("success", true);
    //         response.put("message", "玩家添加成功");
    //     } catch (Exception e) {
    //         response.put("success", false);
    //         response.put("message", "添加玩家失败: " + e.getMessage());
    //     }

    //     return response;
    // }

    /**
     * 获取客户端真实IP地址
     *
     * @param request HTTP请求对象
     * @return 客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0];
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}